package com.crm.system.service.impl.customerManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.NewsEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.MessageManager.Message;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerRelation;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.customerManager.CustomerRelationVO;
import com.crm.model.vo.customerManager.CustomerVO;
import com.crm.redis.mapper.ValueRMapper;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerRelationDbService;
import com.crm.service.messageManager.MessageDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.customerManager.CustomerRelationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ Author ：pym
 * @ Date   ：2021/2/23 10:35
 */
@Service
@Slf4j
public class CustomerRelationServiceImpl implements CustomerRelationService {
    @Autowired
    private CustomerRelationDbService customerRelationDbService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MessageDbService messageDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    /**
     * 查询客户关联
     * @param customerId 客户id
     * @return
     */
    @Override
    public List<CustomerRelation> selectCustomerRelationList(String customerId) {

        String violationTm = redisTemplate.opsForValue().get("Violation_"+customerId);
        if(StringUtils.isBlank(violationTm)) {
            CustomerRelation relation = customerRelationDbService.selectCustomerRelationViolationTm(customerId);
            if(relation != null) {
                relation.setViolationTm(null);
                relation.setDeleteStatus(Short.parseShort("1"));
                customerRelationDbService.updateRelation(relation);
            }
        }

        List<CustomerRelation> list = customerRelationDbService.selectCustomerRelationList(customerId);
        return list;
    }

    /**
     * 新增客户关联
     * @param customerRelation
     * @return
     */
    @Override
    public String addCustomerRelation(CustomerRelation customerRelation) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd");


        String violationTm = redisTemplate.opsForValue().get("Violation_"+customerRelation.getCustomerId());
        if(!StringUtils.isBlank(violationTm)) {
            return "你的账号被封禁,解封时间是"+violationTm;
        }

        List<CustomerRelation> list = customerRelationDbService.selectCustomerRelationList(customerRelation.getCustomerId());
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //信用类型 0可以   1不可以     2正在核验
        if(userAccount.getCreditType() != 0) {
            return "您的信用不足";
        }
        if (list != null && list.size() > 0) {
            for(CustomerRelation relation : list) {
                //查验类型  0正确  1错误 2正在核验
                if(relation.getInspectionType() == 1 ) {
                    return "您的查验类型有错误的";
                }
                if(relation.getInspectionType() == 2) {
                    return "您有关联正在核验中";
                }
            }

            if(list.size() == 3) {
                return "您的曾用名和关联公司只能有3条";
            }
        }
        CustomerVO customerVO = customerDbService.selectCustomerByName(customerRelation.getRelationName());
        if(customerVO != null) {
            return "客户名称已存在,请确认后输入";
        }

        if(!StringUtils.isBlank(customerRelation.getUnifiedSocialCreditCode())) {
            Customer customer = customerDbService.selectCustomerByCode(customerRelation.getUnifiedSocialCreditCode());
            if(customer != null) {
                return "信用代码已存在,请确认后输入";
            }
        }else{
            CustomerVO cust = customerDbService.selectByCustomerId(customerRelation.getCustomerId());
            customerRelation.setUnifiedSocialCreditCode(cust.getUnifiedSocialCreditCode());
        }


        customerRelation.setCustomerRelationId(CommonUtils.getGUID());
        customerRelation.setCreatePeopleId(userAccount.getAccountId());
        customerRelation.setCreateTm(new Date());
        customerRelation.setUpdatePeopleId(userAccount.getAccountId());
        customerRelation.setUpdateTm(new Date());
        customerRelation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        customerRelation.setCustomerId(customerRelation.getCustomerId());
        customerRelation.setCompanyId(userAccount.getCompanyId());
        customerRelationDbService.addCustomerRelation(customerRelation);
        return "success";



    }

    /**
     * 删除客户关联
     * @param customerRelation
     * @return
     */
    @Override
    public Boolean deleteCustomerRelation(CustomerRelation customerRelation) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        customerRelation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
        customerRelation.setUpdateTm(new Date());
        customerRelation.setUpdatePeopleId(userAccount.getAccountId());
        return customerRelationDbService.updateCustomerRelation(customerRelation);
    }

    /**
     * 修改曾用名
     * @param customerRelation
     * @return
     */
    @Override
    public Boolean updateNameUsedBefore(CustomerRelation customerRelation) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Customer customer = customerDbService.selectCustomerById(customerRelation.getCustomerId());

        CustomerRelation relation = new CustomerRelation();
        relation.setCustomerRelationId(customerRelation.getCustomerRelationId());
        relation.setRelationName(customer.getCustomerName());
        if(!StringUtils.isBlank(customerRelation.getUnifiedSocialCreditCode())) {
            relation.setUnifiedSocialCreditCode(customer.getUnifiedSocialCreditCode());
        }
        relation.setUpdateTm(new Date());
        relation.setUpdatePeopleId(userAccount.getAccountId());


        customer.setCustomerName(customerRelation.getRelationName());
        if(!StringUtils.isBlank(customerRelation.getUnifiedSocialCreditCode())) {
            relation.setUnifiedSocialCreditCode(customer.getUnifiedSocialCreditCode());
            customer.setUnifiedSocialCreditCode(customerRelation.getUnifiedSocialCreditCode());
        }
        customer.setUpdateTm(new Date());
        customer.setUpdatePeopleId(userAccount.getAccountId());
        customerRelationDbService.updateCustomerRelation(relation);
        Boolean bs = customerDbService.updateCustomerById(customer);
        return bs;
    }

    /**
     * 曾用名写入信用代码
     * @return
     */
    @Override
    public Boolean updateCustomerRelation() {
        Integer a = 0;
        Date date = new Date();
        List<CustomerRelation> list = customerRelationDbService.selectRelationType(0);
        for (CustomerRelation cc : list) {
            Customer customer = customerDbService.selectCustomerById(cc.getCustomerId());
            if(!StringUtils.isBlank(customer.getUnifiedSocialCreditCode())) {
                if(StringUtils.isBlank(cc.getUnifiedSocialCreditCode())) {
                    cc.setUnifiedSocialCreditCode(customer.getUnifiedSocialCreditCode());
                    cc.setUpdateTm(date);
                    customerRelationDbService.updateCustomerRelation(cc);
                    a+=1;
                }
            }
        }
        log.info("-------" + a.toString());
        return true;
    }

    /**
     * 客户关联审核列表
     * @param pageIndex 页码
     * @param pageSize 条数
     * @param sortName 分组字段
     * @param sortOrder 排序
     * @param dateType 全部  all  本月 thisMonth 本周 thisWeek
     * @param customerName 客户名称
     * @return
     */
    @Override
    public DhPageInfo<CustomerRelationVO> examineCustomerRelationList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder,String dateType,String customerName) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
        }

        List<CustomerRelationVO> customerList = customerRelationDbService.examineCustomerRelationList(dateUnit,customerName);
        PageInfo<CustomerRelationVO> pageInfo = new PageInfo<CustomerRelationVO>(customerList);
        return new DhPageInfo<CustomerRelationVO>(pageInfo, customerList);
    }

    /**
     * 客户核验关联信息
     * @param customerRelation
     * @return
     */
    @Override
    public Boolean aexamineRelation(CustomerRelation customerRelation) throws ParseException {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerRelation relation = customerRelationDbService.selectCustomerRelation(customerRelation.getCustomerRelationId());


        GregorianCalendar now = new GregorianCalendar();
        now.add(GregorianCalendar. MONTH, 6);   //可以是天数或月数  数字自定 -6前6个月
        SimpleDateFormat fmtrq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        Date date = new Date();

        //间隔时间的小时数
        String s = dateDiff(fmtrq.format(date), fmtrq.format(now.getTime()), "yyyy-MM-dd HH:mm:ss");


        //查验类型  0正确  1错误 2正在核验
        if(customerRelation.getInspectionType() == 1) {
            customerRelation.setViolationTm(now.getTime());
            Boolean rs = ValueRMapper.setRedisObject(redisTemplate, "Violation_"+relation.getCustomerId(),fmtrq.format(now.getTime()), Integer.parseInt(s), TimeUnit.HOURS);
            //Boolean rs = ValueRMapper.setRedisObject(redisTemplate, "Violation_"+relation.getCustomerId(),fmtrq.format(now.getTime()), 60, TimeUnit.SECONDS);

            System.out.println(rs);
        }

        customerRelation.setUpdatePeopleId(userAccount.getAccountId());
        Date date1 = new Date();
        customerRelation.setUpdateTm(date1);
        Boolean aBoolean = customerRelationDbService.updateCustomerRelation(customerRelation);
        //发送系统消息流程
        if (aBoolean){
            Message me=new Message();
            me.setMessageId(CommonUtils.getGUID());
            me.setSendCompanyId(userAccount.getCompanyId());
            me.setSenderId(userAccount.getAccountId());
            me.setSendTm(date1);

            //TODO Lxxx 主题id待定
            me.setThemeId(CommonUtils.getGUID());
            me.setTheme("关联审核");
            StringBuffer customerBuffer=new StringBuffer("您所关联的企业 ");
            customerBuffer.append(relation.getRelationName());
            //判断通过未通过
            if (customerRelation.getInspectionType()==0){
                customerBuffer.append(" 审核通过").toString();
            }else {
                customerBuffer.append(" 审核未通过").toString();
            }
            me.setNewsDetail(customerBuffer.toString());
            me.setNewsType(NewsEnum.SYS_MESS.getValue());
            me.setReceiverNewsReadType(NewsEnum.NO_READ.getValue());
            me.setMarkImportant(NewsEnum.NO_IMPORTANT.getValue());
            me.setReceiverId(relation.getCreatePeopleId());
            //根据账号查询公司
            UserAccount receiveUserAccount = userAccountDbService.selectUserAccountByAccountId(relation.getCreatePeopleId());
            me.setReceiverCompanyId(receiveUserAccount.getCompanyId());
            me.setReceiverTm(date1);
            me.setCreatePeopleId(userAccount.getAccountId());
            me.setCreateTm(date1);
            me.setUpdatePeopleId(userAccount.getAccountId());
            me.setUpdateTm(date1);
            me.setDeleteStatus(0);
            messageDbService.addMessage(me);
        }
        return aBoolean;
    }


    /**
     *计算两个时间的小时数
     * @param startTime 前时间
     * @param endTime 后时间
     * @param format yyyy-MM-dd HH:mm:ss
     * @return
     * @throws ParseException
     */
    public static String dateDiff(String startTime, String endTime, String format) throws ParseException {
        //按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000*24*60*60;//一天的毫秒数
        long nh = 1000*60*60;//一小时的毫秒数
        long nm = 1000*60;//一分钟的毫秒数
        long ns = 1000;//一秒钟的毫秒数
        long diff;
        //获得两个时间的毫秒时间差异
        diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        long day = diff/nd;//计算差多少天

        long hour = diff%nd/nh;//计算差多少小时
        long min = diff%nd%nh/nm;//计算差多少分钟
        long sec = diff%nd%nh%nm/ns;//计算差多少秒//输出结果
        long h = day * 24 + hour;

        System.out.println("时间相差："+day+"天"+hour+"小时"+min+"分钟"+sec+"秒。");
        System.out.println("独到的"+h);
        return String.valueOf(h);
    }



}
